#include "player.h"

void player_init(struct player *player) {
    memset(player, 0, sizeof(struct player));
    player->cards = (card *)malloc(0);
}

card player_pop_card(struct player *player) {
    player->card_count--;
    card to_pop = player->cards[player->card_count];
    if (player->card_count % INIT_CARD_PILE_SIZE == 0)
        player->cards = realloc(player->cards, sizeof(card) * (size_t)(INIT_CARD_PILE_SIZE + player->card_count));
    return to_pop;
}

bool player_can_pop(struct player *player, card last_card, int force_draw) {
    for (int i = 0; i < player->card_count; i++) {
        card c = player->cards[i];
        if (card_rank(c) == card_rank(last_card) || card_suit(c) == card_suit(last_card)) {
            if (!force_draw || card_is_special(c)) {
                card_swap(&(player->cards[i]), &(player->cards[player->card_count - 1]));
                return true;
            }
        }
    }
    return false;
}

bool player_choose_card(struct player *player, card c) {
    for (int i = 0; i < player->card_count; i++) {
        if (c.order == player->cards[i].order) {
            card_swap(&(player->cards[i]), &(player->cards[player->card_count - 1]));
            return true;
        }
    }
    return false;
}

void player_push_card(struct player *player, card c) {
    if (player->card_count % INIT_CARD_PILE_SIZE == 0)
        player->cards = realloc(player->cards, sizeof(card) * (size_t)(INIT_CARD_PILE_SIZE + player->card_count));
    player->cards[player->card_count] = c;
    player->card_count++;
}

void player_destroy(struct player *player) {
    free(player->cards);
}
